<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 6.3.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.jpg">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.jpg">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"matian.connorma.cn","root":"/","scheme":"Muse","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="看了下 java 8 中 HashMap 的源码，结合网上一些文章，大概明白了 HashMap 中几个一直很疑惑的地方。这里就记录一下 HashMap 的学习。 数据结构和一些参数的作用HashMap 的数据结构“平平无奇”，就是我们熟悉的“数组+链表”的方式（链地址法），并且在链表长度超过某个值（默认为 8）后，将链表转换为红黑树以提高效率。 HashMap 存储数据的数组是： 1transie">
<meta property="og:type" content="article">
<meta property="og:title" content="令人惊叹的HashMap—数据结构与hash函数">
<meta property="og:url" content="http://matian.connorma.cn/1d720228.html">
<meta property="og:site_name" content="马天">
<meta property="og:description" content="看了下 java 8 中 HashMap 的源码，结合网上一些文章，大概明白了 HashMap 中几个一直很疑惑的地方。这里就记录一下 HashMap 的学习。 数据结构和一些参数的作用HashMap 的数据结构“平平无奇”，就是我们熟悉的“数组+链表”的方式（链地址法），并且在链表长度超过某个值（默认为 8）后，将链表转换为红黑树以提高效率。 HashMap 存储数据的数组是： 1transie">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2019-05-26T13:16:14.000Z">
<meta property="article:modified_time" content="2024-01-25T12:19:17.209Z">
<meta property="article:author" content="马天">
<meta property="article:tag" content="java">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://matian.connorma.cn/1d720228.html">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>令人惊叹的HashMap—数据结构与hash函数 | 马天</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">马天</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://matian.connorma.cn/1d720228.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="马天">
      <meta itemprop="description" content="程序猿">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="马天">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          令人惊叹的HashMap—数据结构与hash函数
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2019-05-26 21:16:14" itemprop="dateCreated datePublished" datetime="2019-05-26T21:16:14+08:00">2019-05-26</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/java/" itemprop="url" rel="index"><span itemprop="name">java</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>看了下 java 8 中 HashMap 的源码，结合网上一些文章，大概明白了 HashMap 中几个一直很疑惑的地方。这里就记录一下 HashMap 的学习。</p>
<h2 id="数据结构和一些参数的作用"><a href="#数据结构和一些参数的作用" class="headerlink" title="数据结构和一些参数的作用"></a>数据结构和一些参数的作用</h2><p>HashMap 的数据结构“平平无奇”，就是我们熟悉的“数组+链表”的方式（链地址法），并且在链表长度超过某个值（默认为 8）后，将链表转换为红黑树以提高效率。</p>
<p>HashMap 存储数据的数组是：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">transient</span> Node&lt;K,V&gt;[] table;</span><br></pre></td></tr></table></figure>

<p>也即一个 Node 数组，Node 实现 Entry 接口，每个 Node 存储一个键值对，如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">final</span> <span class="type">int</span> hash;</span><br><span class="line"><span class="keyword">final</span> K key;</span><br><span class="line">V value;</span><br><span class="line">Node&lt;K,V&gt; next;</span><br></pre></td></tr></table></figure>

<p>其中，hash 是存储的 node 中的 key 的哈希值，key、value 即键和值，而 next 则显然是构建链表的，指向链表的下一个节点。</p>
 <span id="more"></span>

<p>HashMap 中还有一些默认参数，主要是：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * The default initial capacity - MUST be a power of two.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">static</span> <span class="keyword">final</span> <span class="type">int</span> <span class="variable">DEFAULT_INITIAL_CAPACITY</span> <span class="operator">=</span> <span class="number">1</span> &lt;&lt; <span class="number">4</span>; <span class="comment">// aka 16</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * The maximum capacity, used if a higher value is implicitly specified</span></span><br><span class="line"><span class="comment"> * by either of the constructors with arguments.</span></span><br><span class="line"><span class="comment"> * MUST be a power of two &lt;= 1&lt;&lt;30.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">static</span> <span class="keyword">final</span> <span class="type">int</span> <span class="variable">MAXIMUM_CAPACITY</span> <span class="operator">=</span> <span class="number">1</span> &lt;&lt; <span class="number">30</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * The load factor used when none specified in constructor.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">static</span> <span class="keyword">final</span> <span class="type">float</span> <span class="variable">DEFAULT_LOAD_FACTOR</span> <span class="operator">=</span> <span class="number">0.75f</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * The bin count threshold for using a tree rather than list for a</span></span><br><span class="line"><span class="comment"> * bin.  Bins are converted to trees when adding an element to a</span></span><br><span class="line"><span class="comment"> * bin with at least this many nodes. The value must be greater</span></span><br><span class="line"><span class="comment"> * than 2 and should be at least 8 to mesh with assumptions in</span></span><br><span class="line"><span class="comment"> * tree removal about conversion back to plain bins upon</span></span><br><span class="line"><span class="comment"> * shrinkage.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">static</span> <span class="keyword">final</span> <span class="type">int</span> <span class="variable">TREEIFY_THRESHOLD</span> <span class="operator">=</span> <span class="number">8</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * The bin count threshold for untreeifying a (split) bin during a</span></span><br><span class="line"><span class="comment"> * resize operation. Should be less than TREEIFY_THRESHOLD, and at</span></span><br><span class="line"><span class="comment"> * most 6 to mesh with shrinkage detection under removal.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">static</span> <span class="keyword">final</span> <span class="type">int</span> <span class="variable">UNTREEIFY_THRESHOLD</span> <span class="operator">=</span> <span class="number">6</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * The smallest table capacity for which bins may be treeified.</span></span><br><span class="line"><span class="comment"> * (Otherwise the table is resized if too many nodes in a bin.)</span></span><br><span class="line"><span class="comment"> * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts</span></span><br><span class="line"><span class="comment"> * between resizing and treeification thresholds.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">static</span> <span class="keyword">final</span> <span class="type">int</span> <span class="variable">MIN_TREEIFY_CAPACITY</span> <span class="operator">=</span> <span class="number">64</span>;</span><br></pre></td></tr></table></figure>

<p>注释已经讲的很清楚，注意的是容量 capacity 必须是 2 的整数次幂。</p>
<p>field 中注意的是：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * The next size value at which to resize (capacity * load factor).</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@serial</span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="comment">// (The javadoc description is true upon serialization.</span></span><br><span class="line"><span class="comment">// Additionally, if the table array has not been allocated, this</span></span><br><span class="line"><span class="comment">// field holds the initial array capacity, or zero signifying</span></span><br><span class="line"><span class="comment">// DEFAULT_INITIAL_CAPACITY.)</span></span><br><span class="line"><span class="type">int</span> threshold;</span><br></pre></td></tr></table></figure>

<p>当 size（k-v 对数量）超过了 threshold （capacity * load factor）时，将会进行一次扩容。</p>
<h2 id="为什么容量-capacity-必须是-2-n-——-哈希函数和-rehash"><a href="#为什么容量-capacity-必须是-2-n-——-哈希函数和-rehash" class="headerlink" title="为什么容量 capacity 必须是 2^n —— 哈希函数和 rehash"></a>为什么容量 capacity 必须是 2^n —— 哈希函数和 rehash</h2><p>之前一直对这个问题不理解，最近看了一篇文章讲解了这点才恍然大悟，不得不说，在这一约定下，HashMap 实现的非常精妙，尤其是在扩容之后对原有节点的 rehash 中。</p>
<p>先看一下 HashMap 的哈希函数，实现是这样的，</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> <span class="keyword">final</span> <span class="type">int</span> <span class="title function_">hash</span><span class="params">(Object key)</span> &#123;</span><br><span class="line">    <span class="type">int</span> h;</span><br><span class="line">    <span class="keyword">return</span> (key == <span class="literal">null</span>) ? <span class="number">0</span> : (h = key.hashCode()) ^ (h &gt;&gt;&gt; <span class="number">16</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>不管它什么高低位移位，总之，这一函数是根据 key 的 hashCode 计算的哈希值，但是这样算出来的值，显然是无法直接对应到 table 数组的索引的，也即无法直接确定元素位置，那么怎么求出元素处于的位置索引呢？</p>
<p>HashMap 中有一段出现了不知道多少次的 if 判断：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> ((p = tab[i = (n - <span class="number">1</span>) &amp; hash]) == <span class="literal">null</span>)</span><br><span class="line">    ...</span><br></pre></td></tr></table></figure>

<p>这里的 n 是数组 table 的长度（table.length，注意不是 size（k-v 对的数量）），tab[i &#x3D; (n - 1) &amp; hash] 显然是取数组中的值，但是 (n - 1) &amp; hash 怎么就变成了数组索引，让人有些不解。其实这里是一个数学上的现象。</p>
<p>对于 2^n，二进制形式中只有一个 1，其他位全为零（1 不会是在第零位），那么(2^n - 1) 的二进制形式，自然是高 p 位全为 0，低 q 位全为 1。n 即数组长度是 2^n，那么“(n - 1) &amp; hash”的作用就类似于掩码，结果将只保留 n 的范围内的二进制位，(n - 1) &amp; hash 实际上就相当于 hash % n</p>
<p>所以经过这样一个“magic”的操作，就拿到了 key 对应的数组索引，实现了一个哈希函数。</p>
<p>我们都学过，哈希函数中，如果取模的话，值应该是选一个合适大小的素数，比如小于长度的最大素数，但是 HashMap 使用容量取模作为哈希函数，却要求容量是 2 的整数次幂，不细看确实不解，真正让人惊叹的正是这一约定在 rehash 时带来的特性。</p>
<p>每次扩容后，按照约定，newCap &#x3D; oldCap * 2，相应的，对原来存储的节点，需要进行 rehash，移动到在新的数组中的位置。</p>
<p>而 newCap 则就是 oldCap 左移了 1 位（右端补零），这样，与 (newCap - 1) 的 &amp; 运算，如果 hash 在 newCap 的最高的 1 的位置的值是 0，那么 (newCap - 1) &amp; hash 仍是原值，结果不变；而如果这一位置是 1，那么 (newCap - 1) &amp; hash 则相当于增加了 newCap &#x2F; 2 &#x3D; oldCap，结果变成了 (oldCap - 1) &amp; hash + oldCap</p>
<p>说起来比较绕，举个栗子：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">假设原 n = 16 = (10000)B，那么 (n - 1) = 15 = (01111)B，假设 key1 的 hash = (00011)B，那么 (n - 1) &amp; key1.hash 即</span><br><span class="line">  01111</span><br><span class="line">&amp; 00011</span><br><span class="line">—————————</span><br><span class="line">  00011</span><br><span class="line">所以 key1 的索引是 3；</span><br><span class="line">假设 key2 的 hash = (10111)B，那么 (n - 1) &amp; key2.hash 即</span><br><span class="line">  01111</span><br><span class="line">&amp; 10111</span><br><span class="line">—————————</span><br><span class="line">  00111</span><br><span class="line">所以 key2 的索引是 7；</span><br></pre></td></tr></table></figure>

<p>而在扩容一次后，</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">n = 32 = (100000)B，那么 (n - 1) = 31 = (011111)B，key1 的 hash = (00011)B，那么 (n - 1) &amp; key1.hash 即</span><br><span class="line">  011111</span><br><span class="line">&amp; 000011</span><br><span class="line">—————————</span><br><span class="line">  000011</span><br><span class="line">所以 key1 的索引仍然是 3；</span><br><span class="line">key2 的 hash = (10111)B，那么 (n - 1) &amp; key2.hash 即</span><br><span class="line">  011111</span><br><span class="line">&amp; 010111</span><br><span class="line">—————————</span><br><span class="line">  010111</span><br><span class="line">所以 key2 的索引是 (111)B + (10000)B = 7 + 16，即“原索引 + 原容量”</span><br></pre></td></tr></table></figure>
<p>以上栗子中，对比扩容时 key1 和 key2 的情况，不难发现，扩容后索引要么是原值不变，要么是“原索引 + 原容量”，而两种情况只需要判断第 4 位的值是 0 还是 1 即可区分。</p>
<p>所以我们可以看到 resize() 函数中有这么一段“神秘莫测”的代码，使用 newCap &amp; hash 判断元素位置是否需要移动：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">Node&lt;K,V&gt; loHead = <span class="literal">null</span>, loTail = <span class="literal">null</span>;</span><br><span class="line">Node&lt;K,V&gt; hiHead = <span class="literal">null</span>, hiTail = <span class="literal">null</span>;</span><br><span class="line">Node&lt;K,V&gt; next;</span><br><span class="line"><span class="keyword">do</span> &#123;</span><br><span class="line">    next = e.next;</span><br><span class="line">    <span class="keyword">if</span> ((e.hash &amp; oldCap) == <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (loTail == <span class="literal">null</span>)</span><br><span class="line">            loHead = e;</span><br><span class="line">        <span class="keyword">else</span></span><br><span class="line">            loTail.next = e;</span><br><span class="line">        loTail = e;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (hiTail == <span class="literal">null</span>)</span><br><span class="line">            hiHead = e;</span><br><span class="line">        <span class="keyword">else</span></span><br><span class="line">            hiTail.next = e;</span><br><span class="line">        hiTail = e;</span><br><span class="line">    &#125;</span><br><span class="line">&#125; <span class="keyword">while</span> ((e = next) != <span class="literal">null</span>);</span><br><span class="line"><span class="keyword">if</span> (loTail != <span class="literal">null</span>) &#123;</span><br><span class="line">    loTail.next = <span class="literal">null</span>;</span><br><span class="line">    newTab[j] = loHead;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">if</span> (hiTail != <span class="literal">null</span>) &#123;</span><br><span class="line">    hiTail.next = <span class="literal">null</span>;</span><br><span class="line">    newTab[j + oldCap] = hiHead;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="key-到底怎样才是相同"><a href="#key-到底怎样才是相同" class="headerlink" title="key 到底怎样才是相同"></a>key 到底怎样才是相同</h2><p>也是一段出现了不知道多少次的判断：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (e.hash == hash &amp;&amp; </span><br><span class="line">    ((k = e.key) == key || (key != <span class="literal">null</span> &amp;&amp; key.equals(k))))</span><br></pre></td></tr></table></figure>

<p>就是在以下情况下认为是相同的 key：</p>
<ol>
<li>求出的 hash 值相同（根据 hashCode() 的值求出，即是比较  hashCode() 是否相同）</li>
<li>满足 1 的情况下，（key 是否是相同引用，或者都是 null（key 可以是 null，并且 null 和 null 也认为是相等）） || （key1.equals(key2) 返回 true）</li>
</ol>
<p>搞清楚了 HashMap 的哈希函数和 HashMap 到底认为什么情况下 key 才是相同的这两个问题之后，那么 get&#x2F;put 函数的大致流程也就清楚了（table 是否为空 -&gt; 查找 key -&gt; 遍历链表&#x2F;查找红黑树，table 是否为空，空时 resize() -&gt; 查找 key -&gt; 遍历链表&#x2F;查找红黑树 -&gt; 找到替换&#x2F;找不到放入 -&gt; 链表长度大于 8 时转换为红黑树 -&gt; 需要时进行扩容）。</p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/java/" rel="tag"># java</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/6d9ffe57.html" rel="prev" title="令人费解的ThreadLocal">
      <i class="fa fa-chevron-left"></i> 令人费解的ThreadLocal
    </a></div>
      <div class="post-nav-item">
    <a href="/bfd4b596.html" rel="next" title="Servlet filter记录">
      Servlet filter记录 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E5%92%8C%E4%B8%80%E4%BA%9B%E5%8F%82%E6%95%B0%E7%9A%84%E4%BD%9C%E7%94%A8"><span class="nav-number">1.</span> <span class="nav-text">数据结构和一些参数的作用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%BA%E4%BB%80%E4%B9%88%E5%AE%B9%E9%87%8F-capacity-%E5%BF%85%E9%A1%BB%E6%98%AF-2-n-%E2%80%94%E2%80%94-%E5%93%88%E5%B8%8C%E5%87%BD%E6%95%B0%E5%92%8C-rehash"><span class="nav-number">2.</span> <span class="nav-text">为什么容量 capacity 必须是 2^n —— 哈希函数和 rehash</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#key-%E5%88%B0%E5%BA%95%E6%80%8E%E6%A0%B7%E6%89%8D%E6%98%AF%E7%9B%B8%E5%90%8C"><span class="nav-number">3.</span> <span class="nav-text">key 到底怎样才是相同</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">马天</p>
  <div class="site-description" itemprop="description">程序猿</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">41</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">17</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">25</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/matian2014" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;matian2014" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:matian1103@qq.com" title="E-Mail → mailto:matian1103@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        
  <div class="beian"><a href="https://beian.miit.gov.cn/" rel="noopener" target="_blank">陕ICP备2023001563号 </a>
  </div>

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2025</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">马天</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://muse.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
